package Servlet.admin;

import Utils.DruidUtils;
import domain.News;
import domain.NewsType;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import service.AdminService;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

@WebServlet("/admin/modifyData")
public class ModifyData extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Long newsId1 = 0L;
        Long newsId2 = 0L;
        AdminService.id = Long.parseLong(request.getParameter("newsId1"));
//        AdminService.id = Long.parseLong(request.getParameter("newsId"));
        if ((newsId1 = Long.parseLong(request.getParameter("newsId1") == null ? "0" : request.getParameter("newsId1"))) != 0L) {

            try {
                String sql = "select n.news_id as newsId, n.news_title as newsTitle, n.news_content as newsContent, n.news_date as newsDate, n.news_image as newsImage, nt.news_type_name as newsTypeName, nt.news_type_id as newsTypeId from " +
                        "javawebsql.news as n join javawebsql.news_type as nt on " +
                        "nt.news_type_id = n.news_type_id where n.news_id = ?";

                QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
                News newsData = queryRunner.query(sql, new BeanHandler<>(News.class), newsId1);

                List<NewsType> newsTypeList1 = AdminService.getNewsType();

//                System.out.println("newsData"+newsData);
                request.setAttribute("newsTypeList1",newsTypeList1);
                request.setAttribute("newsData", newsData);
            } catch (Exception e) {
//                System.out.println(e);
                throw new RuntimeException(e);
            }

            request.getRequestDispatcher("/admin/modify.jsp").forward(request, response);
        }

        if ((newsId2 = Long.parseLong(request.getParameter("newsId2") == null ? "0" : request.getParameter("newsId2"))) != 0L) {
            System.out.println("删除");
            String sql = "delete from news where news_id=?;";
            QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
            try {
                queryRunner.execute(sql, new BeanHandler<>(News.class), newsId2);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            request.getRequestDispatcher("../admin/newsManagement").forward(request, response);
        }


    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        response.setCharacterEncoding("utf-8");
//        request.setCharacterEncoding("utf-8");
//        Long newsId = Long.parseLong(request.getParameter("newsId1"));
        Long newsTypeId = 0L;
        String newsTitle = null;
        String newsContent = null;
        String newsDateTime = null;
        String fileName = null;

        DiskFileItemFactory factory = new DiskFileItemFactory();

        ServletContext context = request.getServletContext();
        File f = new File(context.getInitParameter("tmp"));

        if (!f.exists()) {
            f.mkdirs();
        }
        factory.setRepository(f);

        ServletFileUpload fileUpload = new ServletFileUpload(factory);
//        fileUpload.setHeaderEncoding("utf-8");
        try {
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            for (FileItem fileItem : fileItems) {
                fileName = fileItem.getFieldName();
                if (fileItem.isFormField()) {
                    System.out.println("普通文件");
                    if ("newsTypeId".equals(fileName)) {
                        newsTypeId = Long.parseLong(fileItem.getString());
                    }
                    if ("title".equals(fileName)) {
                        newsTitle = fileItem.getString("UTF-8");
                    }
                    if ("content".equals(fileName)) {
                        newsContent = fileItem.getString("UTF-8");
                    }
                    if ("datetime".equals(fileName)) {
                        newsDateTime = fileItem.getString();
                    }
                } else {
                    fileName = fileItem.getName();
                    String s = UUID.randomUUID().toString();
                    fileName = s + fileName.substring(fileName.lastIndexOf("."));
                    FileOutputStream out = new FileOutputStream("D:\\app_bc\\Run\\JavaWeb\\javaweb\\web\\images\\content-images\\" + fileName);
                    InputStream inputStream = fileItem.getInputStream();
                    int len = 0;
                    byte[] buffer = new byte[1024];
                    while ((len = inputStream.read(buffer)) > 0) {
                        out.write(buffer, 0, len);
                    }
                    inputStream.close();
                    out.close();
                }
            }
        } catch (FileUploadException e) {
            throw new RuntimeException(e);
        }

        AdminService.updateData(newsTypeId, newsTitle, newsContent, newsDateTime, AdminService.id);
//        request.setAttribute("news", news);

        request.getRequestDispatcher("../admin/newsManagement").forward(request, response);
    }
}
